package com.cn.data.thread.countdownlatch;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author: chenl
 * @Date: 2019/3/2 23:34
 */
public class ApplicationStartupUtil {

   private static List<BaseHealthChecker> services;

   private static CountDownLatch countDownLatch;

   private final static ApplicationStartupUtil INSTANCE = new ApplicationStartupUtil();

   private static  Executor executor = new ThreadPoolExecutor(3, 3, 60 ,
    TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100));

   private ApplicationStartupUtil(){

   }

   public static ApplicationStartupUtil instance(){
       return INSTANCE;
   }

   public static boolean checkExternalServices() throws InterruptedException {
       countDownLatch = new CountDownLatch(3);

       //All add checker in lists
       services = new ArrayList<>();
       services.add(new NetworkHealthChecker(countDownLatch));
       services.add(new CacheHealthChecker(countDownLatch));
       services.add(new DatabaseHealthChecker(countDownLatch));

       for (BaseHealthChecker service : services){
           executor.execute(service);
       }

       countDownLatch.await();
        for (BaseHealthChecker service : services){
            if (!service.isSericeUp()){
                return false;
            }
        }

       return true;
   }
}
